import es

from wcs.libs.constants import *
from wcs.libs.database.sqlite import SQLiteManager

databasePath = DATA_PATH.joinpath("data.sqlite")
database     = None
DATABASE_SYSTEM = SQLiteManager
DATABASE_ARGS   = (databasePath, )

__all__ = ["getDatabaseMethod", "setDatabaseMethod", "getDatabase"]

def getDatabase():
    """
    Returns the database object for the current API loaded. This allows us to
    return a non-static object, as the database object could change at any time.
    
    @return SQLBase The base object of the database API.
    """
    return database

def getDatabaseMethod():
    """
    Obtains the current database system and the arguments passed into the
    constructor.

    @return tuple 2 item tuple cotnaining (system, arguments).
        o system - the current database management system
        o arguments - a tuple containing any constructor parameters
    """
    return (DATABASE_SYSTEM, DATABASE_ARGS)
    
def setDatabaseMethod(databaseSystem, databaseArgs, reloadDatabase=False):
    """
    Reassigns the current database method and database arguments to the new
    values. This allows us to alter the database management system that WCS
    uses. By default, it will use SQLiteManager object.

    @param base.SQLBase databaseSystem A database system to manage the objects,
                                       must accept all public functions of the
                                       SQLiteManager class.
    @param tuple databaseArgs Any arguments passed into the constructor of the
                              database system.
    @param bool reloadDatabase Whether or not the database will be reopened
                               under the new database management system.
    """
    from wcs.libs.players import players
    
    global DATABASE_SYSTEM
    global DATABASE_ARGS
    global database
    DATABASE_SYSTEM = databaseSystem
    DATABASE_ARGS   = databaseArgs
    if reloadDatabase is True:
        if database is not None:
            for player in es.getUseridList():
                players[player].commit()
            database.save()
            database.close()
            database = DATABASE_SYSTEM(*DATABASE_ARGS)
            for player in es.getUseridList():
                players[player].refresh()
            es.server.cmd("mp_restartgame 1")
        else:
            database = DATABASE_SYSTEM(*DATABASE_ARGS)
            if es.getplayercount():
                for player in es.getUseridList():
                    players[player].refresh()
                es.server.cmd("mp_restartgame 1")   